package com.mhxy.service.impl;

import com.mhxy.constant.PicConstants;
import com.mhxy.enums.Coord;
import com.mhxy.handler.TaskProgressHandler;
import com.mhxy.service.AbstractTask;
import com.mhxy.util.FuzzyPicUtil;
import com.mhxy.util.MouseUtil;
import com.mhxy.util.ThreadUtil;
import com.sun.jna.platform.win32.WinDef;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FightGhostImpl extends AbstractTask {

    private final String hwndName;

    public FightGhostImpl(WinDef.HWND hwnd_0, String hwndName) {
        super(hwnd_0);
        this.hwndName = hwndName;
    }

    @Override
    public String getTaskName() throws Exception {
        return "抓鬼";
    }

    @Override
    public Boolean before() throws Exception {
        clickEsc1();
        return goToJianYe();
    }

    @Override
    public Boolean execute() throws Exception {
        // 先检查任务列表是否存在，存在则直接点击开始任务
        if (findAndClickTaskList(PicConstants.抓鬼任务_任务列表标志)) {
            return true;
        }

        // 点击日常活动
        if (!findAndClickActivity()) {
            return false;
        }

        // 点击任务图标
        if (!findAndClickTaskTitle(PicConstants.抓鬼任务_任务图标标题, new String[]{})) {
            return false;
        }

        // 点击接受任务
        if (!acceptTask()) {
            log.info("【{}】接受任务失败！", getTaskName());
            return false;
        }

        return true;
    }

    @Override
    public Boolean after() throws Exception {
        int count = 0;
        for (int i = 1; i < 99999; i++) {
            // 战斗时间
            findBattle();
            // 是否停止任务
            if (!TaskProgressHandler.checkHwndUserThreadIsRun(hwndName)) {
                TaskProgressHandler.updateProgress(getTaskName(), "停止");
                // 随便点一下，让队伍停下来
                MouseUtil.lClickRandom(hwnd_0, Coord.SECRET_DRAG_XY.getX(), Coord.SECRET_DRAG_XY.getY());
                return false;
            }
            // 是否已结束
            if (FuzzyPicUtil.findPic(hwnd_0, PicConstants.抓鬼任务_任务结束, 3).isFinded()) {
                count++;
                TaskProgressHandler.updateProgress(getTaskName(), count + "轮");
                if (FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_0, PicConstants.抓鬼任务_再来一次, 3)) {
                    if (!acceptTask()) {
                        log.info("【{}】重新接受任务失败！", getTaskName());
                        return false;
                    }
                }
            }
        }
        return true;
    }

    private boolean acceptTask() throws Exception {
        ThreadUtil.sleep(5000);
        // 点击接受任务
        if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, PicConstants.抓鬼任务_任务接受,3)) {
            return false;
        }
        ThreadUtil.sleep1();
        clickEsc1();
        ThreadUtil.sleep1();
        // 点击任务列表开始任务
        if (findAndClickTaskList(PicConstants.抓鬼任务_任务列表标志)) {
            return true;
        }

        return false;
    }
}
